import { Meta, StoryObj } from "@storybook/react/*";
import AutoComplete, { DataSourceType } from "./autoComplete";
import { ComponentProps } from "react";
import Button from "../Button/button";

type DataType = { value: string, number?: number };

type StoryProps = ComponentProps<typeof AutoComplete> & {testData: DataType[]};

const meta: Meta<StoryProps> = {
    component: AutoComplete,
    title: 'Components/AutoComplete',
    tags: ['autodocs'],
    args: {
        testData: [
            { value: 'bradley', number: 11 },
            { value: 'pope', number: 1 },
            { value: 'caruso', number: 4 },
            { value: 'cook', number: 2 },
            { value: 'cousins', number: 15 },
            { value: 'james', number: 23 },
            { value: 'AD', number: 3 },
            { value: 'green', number: 14 },
            { value: 'howard', number: 39 },
            { value: 'kuzma', number: 0 },
        ]
    }
}
export default meta;

type Story = StoryObj<StoryProps>;

export const Test: Story = {
    name: '测试一下',
    render: (args) => {

        const handleFetch = (query: string) => {
            return args.testData.filter(item => item.value.includes(query));
        }

        const renderOption = (data: DataSourceType<DataType>) => {
            const {value, number} = data;
            return (
                <div>
                    <h3>Name: {value}</h3>
                    <p>Number: {number}</p>
                </div>
            )
        }

        return (
            <AutoComplete fetchSuggestions={handleFetch} renderOption={renderOption} />
        )
    }
}

export const TestAsync: Story = {
    name: '测试异步请求',
    render: (args) => {
        const handleFetch = (query: string) => {
            return fetch(`https://api.github.com/search/users?q=${query}`)
                    .then(res => res.json())
                    .then(({items}) => {
                        return items.slice(0, 10)
                        .map((item: any) => ({value: item.login, ...item}));
                    });
        }

        // const renderOption = (data: DataSourceType<DataType>) => {
        //     const {value, number} = data;
        //     return (
        //         <div>
        //             <h3>Name: {value}</h3>
        //             <p>Number: {number}</p>
        //         </div>
        //     )
        // }

        return (
            <AutoComplete fetchSuggestions={handleFetch} />
        )
    }
}